package com.yyb.controller;

import com.alibaba.fastjson2.JSON;
import com.yyb.annotation.AppPermission;
import com.yyb.annotation.Log;
import com.yyb.common.PageInfo;
import com.yyb.common.Result;
import com.yyb.config.QiniuProperties;
import com.yyb.constants.CoreConstant;
import com.yyb.domain.SysUser;
import com.yyb.dto.SysUserAddDTO;
import com.yyb.dto.SysUserPasswordDTO;
import com.yyb.dto.SysUserQueryDTO;
import com.yyb.dto.SysUserUpdateDTO;
import com.yyb.enums.BusinessType;
import com.yyb.enums.ResultEnums;
import com.yyb.exception.BusinessException;
import com.yyb.service.SysUserService;
import com.yyb.utils.SecurityUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 描述: [用户管理相关的接口]
 * 
 * 
 */
@Tag(name = "用户管理相关的接口")
@RestController
@RequestMapping("sysUser")
public class SysUserController extends BaseController {

    @Resource
    private SysUserService sysUserService;

    /**
     * 分页查询用户
     * POST http://127.0.0.1:8080/sysUser/getByPage
     * 接口ID：148742220
     * 接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742220
     */
    @Operation(summary = "分页查询用户数据")
    @PostMapping("getByPage")
    @AppPermission(value = "system:user:query")
    public Result<PageInfo<SysUser, SysUserQueryDTO>> getByPage(
            @RequestBody PageInfo<SysUser, SysUserQueryDTO> pageInfo) {
        PageInfo<SysUser, SysUserQueryDTO> info = this.sysUserService.getByPage(pageInfo);
        return new Result<>(ResultEnums.SUCCESS, info);
    }

    /**
     * 根据用户ID查询用户数据
     * GET http://127.0.0.1:8080/sysUser/get/{userId}
     * 接口ID：148742222
     * 接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742222
     */
    @Operation(summary = "根据用户ID查询用户数据")
    @GetMapping("get/{userId}")
    @AppPermission(value = "system:user:query")
    public Result<SysUser> get(@PathVariable Long userId) {
        SysUser sysUser = this.sysUserService.queryUserById(userId);
        return new Result<>(ResultEnums.SUCCESS, sysUser);
    }

    /**
     * 添加用户
     * POST http://127.0.0.1:8080/sysUser/save
     * 接口ID：148742221
     * 接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742221
     */
    @Operation(summary = "添加用户")
    @PostMapping("save")
    @AppPermission(value = "system:user:add")
    @Log(title = "用户管理-添加",businessType = BusinessType.INSERT)
    public Result<?> save(@RequestBody  @Validated SysUserAddDTO sysUserAddDTO) {
        int row = this.sysUserService.insert(sysUserAddDTO);
        return this.toAjax(row > 0);
    }

    /**
     * 修改用户
     *   PUT http://127.0.0.1:8080/sysUser/update
     *   接口ID：148742223
     *   接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742223
     * @param sysUserUpdateDTO
     * @return
     */
    @Operation(summary = "修改用户")
    @PutMapping("update")
    @AppPermission(value = "system:user:update")
    @Log(title = "用户管理-修改",businessType = BusinessType.UPDATE)
    public Result<?> save(@RequestBody @Validated SysUserUpdateDTO sysUserUpdateDTO) {
        int row = this.sysUserService.updateByPrimaryKey(sysUserUpdateDTO);
        return this.toAjax(row > 0);
    }

    /**
     * 删除用户
     *   DELETE http://127.0.0.1:8080/sysUser/delete/{userId}
     *   接口ID：148742224
     *   接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742224
     */
    @Operation(summary = "删除用户")
    @DeleteMapping("delete/{userId}")
    @AppPermission(value = "system:user:remove")
    @Log(title = "用户管理-删除",businessType = BusinessType.DELETE)
    public Result<?> delete(@PathVariable Long userId) {
        int row = this.sysUserService.deleteByPrimaryKey(userId);
        return this.toAjax(row > 0);
    }

    /**
     * 重置用户密码
     *   GET http://127.0.0.1:8080/sysUser/resetPwd/{userId}
     *   接口ID：148742225
     *   接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742225
     */
    @Operation(summary = "重置用户密码")
    @GetMapping("resetPwd/{userId}")
    @AppPermission(value = "system:user:resetPwd")
    @Log(title = "用户管理-重置密码",businessType = BusinessType.UPDATE)
    public Result<?> resetPwd(@PathVariable Long userId) {
        int row = this.sysUserService.resetPwd(userId);
        return this.toAjax(row > 0);
    }

    /**
     * 修改用户密码
     */
    @Operation(summary = "修改用户密码")
    @PutMapping("updateUserPwd")
    @Log(title = "用户管理-修改用户密码",businessType = BusinessType.UPDATE)
    public Result<?> updateUserPwd(@RequestBody @Validated SysUserPasswordDTO sysUserPasswordDTO) {
        SysUser currentUser = SecurityUtils.getCurrentUser();
        Long userId = currentUser.getUserId();
        SysUser sysUser = this.sysUserService.queryUserById(userId);
        String md5Hash = DigestUtils.md5DigestAsHex(sysUserPasswordDTO.getOldPassword().getBytes());
        if(!md5Hash.equals(sysUser.getPassword())){
            throw new BusinessException("旧密码不正确");
        }
        int row=this.sysUserService.updateByPassword(userId,sysUserPasswordDTO.getNewPassword());
        return this.toAjax(row > 0);
    }

    @Resource
    private QiniuProperties properties;
    /**
     * 上传用户头像
     */
    @Operation(summary = "上传用户头像")
    @PostMapping("uploadUserAvatar")
    @Log(title = "用户管理-上传用户头像",businessType = BusinessType.OTHER)
    public Result<?> uploadUserAvatar(MultipartFile file) {
        SysUser currentUser = SecurityUtils.getCurrentUser();
        Long userId = currentUser.getUserId();
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = properties.getAk();
        String secretKey = properties.getSk();
        String bucket = properties.getBucket();
        String key = null;
        //登录七牛云拿token
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getInputStream(), null, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            //把头像地址保存到数据库
            String path = properties.getUrl() + putRet.hash;
            int row=this.sysUserService.uploadUserAvatar(userId,path);
            if(row==0){
                throw new BusinessException("保存头像失败");
            }
            return new Result<>(ResultEnums.SUCCESS,path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<>(ResultEnums.ERROR);
    }

}
